import joblib
import pandas as pd
from scale_risk_model import compute_scale_risk

def combine_risk(tree_model_path, preprocessor_path, data_path, annual_credit, alpha=0.6):
    clf = joblib.load(tree_model_path)
    preprocessor = joblib.load(preprocessor_path)
    df_base = pd.read_excel(data_path, sheet_name=0)
    X = df_base.drop(columns=['企业代号', '是否违约'])
    X_proc = preprocessor.transform(X)
    df_base['tree_risk'] = clf.predict_proba(X_proc)[:,1]
    scale_df = compute_scale_risk(data_path, annual_credit)
    df = df_base.merge(scale_df, on='企业代号', how='left')
    df['combined_risk'] = alpha * df['tree_risk'] + (1 - alpha) * df['scale_risk_norm'].fillna(0)
    return df[['企业代号', 'combined_risk']]